<template>
  <div class="article-list">
    <van-pull-refresh v-model="isLoading"
                      success-text="刷新成功"
                      @refresh="onRefresh">
      <van-list v-model="loading"
                :finished="finished"
                finished-text="没有更多了"
                @load="onLoad">
        <article-item v-for="(item,i) in list"
                      :key="i"
                      :title="item"
                      :article="item"
                      :number="item.id"></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from './article-item'
import { list } from '@/static/article-list'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [], // 存储列表数据的数组
      loading: false, // 控制加载中 loading 状态
      finished: false, // 控制数据加载结束的状态
      isLoading: false,
      // 列表数据
      result: [],
      // 控制下拉刷新数据
      freshnum: 0
    }
  },
  created () {
    list.forEach(val => {
      var a = this.channel.id
      if (val.id === a || val.id === a - 3 || val.id === a - 6) {
        this.result = val.result
      }
    })
  },
  methods: {
    // 初始化或滚动到底部的时候会触发调用 onLoad
    onLoad () {
      this.refresh()
    },
    onRefresh () {
      this.list = []
      this.freshnum = this.result.length < this.freshnum + 20 ? 0 : this.freshnum + 10
      this.refresh()
    },
    refresh () {
      this.loading = true
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(() => {
        // 2. 把请求结果数据放到 list 数组中
        for (let i = this.freshnum; i < this.freshnum + 10; i++) {
          this.list.push(this.result[i])
        }
        this.list.forEach(val => { val.photoid = val.textid.toString().slice(0, 1) })
        // 3. 本次数据加载结束之后要把加载状态设置为结束
        //     loading 关闭以后才能触发下一次的加载更多
        this.loading = false
        this.isLoading = false
        // 4. 判断数据是否全部加载完成
        if (this.list.length >= 40) {
          // 如果没有数据了，把 finished 设置为 true，之后不再触发加载更多
          this.finished = true
        }
      }, 1000)
    }

  }
}
</script>

<style scoped lang="less">
  .article-list {
    position: fixed;
    top: 180px;
    bottom: 100px;
    right: 0;
    left: 0;
    overflow-y: auto;
  }
</style>
